<template>
	<view :key="$u.guid()">
		<view class="" @click="close" :key="$u.guid()">
			<slot></slot>
		</view>
		<u-popup :show="popupShow" @close="close" mode="bottom" :round="24" :closeable='true'
			:safeAreaInsetBottom='false'>
			<view class="boxbg" v-if="productDetails.attr">
				<view class="head">
					<image :src="selectAttrValue.image" mode="" v-if="Object.keys(selectAttrValue).length && selectAttrValue.image"></image>
					<image :src="productDetails.image" mode="" v-else></image>
					<view class="itemr">
						<view class="itemr_t">
							<text style="width: 420rpx;">{{productDetails.store_name}}</text>
							<!-- <text>月销{{productDetails.sales}}</text> -->
							<text v-if="Object.keys(selectAttrValue).length">
								销售{{selectAttrValue.sales}}/{{productDetails.unit_name}}
							</text>
							<text v-else>销售{{productDetails.sales}}/{{productDetails.unit_name}}</text>
						</view>
						<view class="itemr_b" v-if="Object.keys(selectAttrValue).length">
							￥{{selectAttrValue.price}}<text>￥{{selectAttrValue.ot_price|| ''}}</text>
						</view>
						<view class="itemr_b" v-else>
							￥{{productDetails.price}}<text>￥{{productDetails.ot_price}}</text>
						</view>
					</view>
				</view>
				<scroll-view scroll-y="true" style="height: 620rpx;">
					<view class="" v-if="productDetails.attr.length == 0">
						<!-- 单规格 -->
					</view>
					<view class="item" v-for="(attr,index) in productDetails.attr" :key="attr.attr_name" v-else>
						<text>{{attr.attr_name}}</text>
						<view class="">
							<template v-for="(attrValue,index2) in attr.attr_value">
								<view @click.stop="updateAttrValue(attrValue,attr)"
									:class="attrValue.check ? 'actives':''" :key="attrValue.attr">
									{{attrValue.attr}}
								</view>
							</template>
						</view>
					</view>
				</scroll-view>
				<view class="num">
					<text>数量</text>
					<view class="">
						<view class="" @click="subtract">
							<image src="https://jw.xzsw2021.com/static/client/icon_83@2x.png" mode=""></image>
						</view>
						<input type="text" disabled v-model="num">
						<view class="" @click="increase">
							<image src="https://jw.xzsw2021.com/static/client/icon_84@2x.png" mode=""></image>
						</view>
					</view>
				</view>
				<view class="addcart" v-if="shop" @click="buy">立即购买</view>
				<view class="addcart" v-else @click="addCart">加入购物车</view>
			</view>
		</u-popup>
		<!-- </u-transition> -->
	</view>
</template>

<script>
	import {
		addCartApi
	} from '@/api/cart.js'
	import {
		getProductDetaiApi
	} from '@/api/product.js'
	import {
		orderCheckApi,
	} from '@/api/order.js'
	import Cache from '@/util/cache.js'
	export default {
		name: "rules",
		data() {
			return {
				num: 1, //shop number
				popupShow: false,
				selectAttrValue: {}, //选中的多规格
				productDetails: {}, //商品详情
				isSetProduct: false,
				skuAll: ''
			};
		},
		props: {
			product: { //标准商品详情
				type: Object,
				default: {},
				immediate: true
			},
			product_id: {
				//或者直接商品id
				type: Number,
				default: 0
			},
			shop: { //是否为立即购买
				type: Boolean,
				default: false,
				required: true
			},
			callbackFunction: {
				type: Function,
				default: null
			},
			group_buying_id: { //平团别人的团
				type: Number,
				default: 0,
				required: true
			}
		},
		watch: {
			product(val, oldVal) {
				
				console.log(val, '^^^^^^^^^^^^^^^')
				if (this.isSetProduct) {
					return;
				}
				if (val) {
					this.productDetails = val
					this.$set(this.productDetails,val)
				}
				if (val.attr) {
					this.setProductAttrDefaultSelect()
				}
			},
			productDetails(val, oldVal) {
				
				console.log({
					val,
					oldVal
				})
			}
		},
		updated() {

		},
		mounted() {
			
			this.popupShow = this.show
		},
		methods: {
			//设置商品属性默认选中一个
			setProductAttrDefaultSelect() {
				
				let This = this
				this.skuAll = Object.keys(this.productDetails.sku).join('@')
				this.skuAll = `@${this.skuAll}@`

				console.log(this.skuAll, 'this.skuAllthis.skuAll')
				if (this.productDetails.attr.length == 0) { //单规格
					this.selectAttrValue = this.productDetails.sku['']
				} else { //多规格
					console.log('发放颠三倒四多多所多')
					let skuIndex = ''
					this.productDetails.attr.forEach((attr, index_) => {
						let count = attr.attr_value.length
						let isOne = true;
						if (index_ == 0) {
							console.log(attr, "::::::")
						}
						attr.attr_value.forEach((attrValue, index) => { //默认给最后一个属性选中
							let is = This.skuAll.search(`,${attrValue.attr},`)
							index += 1
							// console.log(This.skuAll, `,${attrValue.attr},`, is, 'isisis')
							// if (count == index) {
							// 	attrValue.is = true
							// } else {
							// 	attrValue.is = false
							// }
							if (count == index) {
								attrValue.check = true
								if (skuIndex) {
									skuIndex += `,${attrValue.attr}`
								} else {
									skuIndex = attrValue.attr
								}
							}
						})
					})
					console.log(this.productDetails, 'attr_valueattr_value')
					if (this.productDetails.sku[skuIndex])
						this.selectAttrValue = this.productDetails.sku[skuIndex]
				}
			},
			updateAttrValue(attr, attrs) {
				
				console.log({
					attr,
					attrs
				})
				console.log('手动更新')
				attrs.attr_value.forEach(attrValue => {
					attrValue.check = false
				})
				attr.check = true
				this.num = 0
				let selectAttrKey = ''
				this.productDetails.attr.forEach(attrData => {
					attrData.attr_value.forEach(attrValue => {
						if (attrValue.check) {
							if (selectAttrKey) {
								selectAttrKey = selectAttrKey + ',' + attrValue.attr
							} else {
								selectAttrKey = attrValue.attr
							}
						}
					})
				})
				this.selectAttrValue = {}
				if (this.productDetails.sku[selectAttrKey]) {
					this.num = 1
					this.selectAttrValue = this.productDetails.sku[selectAttrKey]
					console.log(this.selectAttrValue)
				} else {
					uni.showToast({
						title: "所选择的规格未开启",
						icon: "none"
					})
				}
			},
			close() {
				let This = this
				this.popupShow = !this.popupShow
				if (this.callbackFunction) {
					this.callbackFunction()
				}
				if (!this.popupShow) {

					return;
				}
				// if (this.productDetails.attr && this.productDetails.sku) {
				// 	return;
				// }
				// console.log(this.productDetails)
				if (!this.product_id) {
					return;
				}
				//非标准的商品详情过来的
				getProductDetaiApi(this.product_id).then(res => {
					This.productDetails = res.data
					This.setProductAttrDefaultSelect()
				}).catch(err => {
					this.popupShow = false
				})
			},
			setProduct(product, group_order_id) {
				this.isSetProduct = true
				console.log(product, "？？？？？？、")
				this.productDetails = product
				this.group_buying_id = group_order_id
			},
			increase() {
				
				if (Object.keys(this.selectAttrValue).length == 0) {
					uni.showToast({
						title: "请先选商品规格",
						icon: "none"
					})
					return;
				}
				this.num += 1
			},
			addCart() {
				
				if (Object.keys(this.selectAttrValue).length == 0) {
					uni.showToast({
						title: "请先选商品规格",
						icon: "none"
					})
					return;
				}

				let cartData = {
					cart_num: this.num,
					is_new: 0,
					product_attr_unique: this.selectAttrValue.unique,
					product_type: this.productDetails.product_type,
					product_id: this.productDetails.product_id
				}
				addCartApi(cartData).then(res => {
					this.popupShow = false
					if (this.callbackFunction !== null) {
						this.callbackFunction()
					}
					uni.showToast({
						title: "加入成功",
						icon: "none"
					})
				}).catch(err => {

				})
			},
			subtract() {
				
				this.num -= 1
				if (this.num <= 1) {
					this.num = 1
				}
			},
			buyGoupOrder() {
				let cartData = {
					cart_num: this.num,
					is_new: 1,
					product_attr_unique: this.selectAttrValue.unique,
					product_type: this.productDetails.product_type,
					product_id: this.productDetails.product_group_id,
					group_buying_id: this.group_buying_id,
					product_id: this.product_id?this.product_id:this.productDetails.product_group_id
				}
				console.log(cartData,'cartDatacartDatacartDatacartDatacartData')
				
				addCartApi(cartData).then(res => {
					let data = {
						address_id: '',
						cart_id: [res.data.cart_id],
						use_integral: false,
					}
					return orderCheckApi(data)
				}).then(res => {
					let data = []
					res.data.order.forEach(merOrder => {
						merOrder.list.forEach(cartData => {
							data.push(cartData)
						})
						Cache.set('cartToPayCheck', data)
					})
					uni.navigateTo({
						url: '/pages/client/order/order-sure/order-sure'
					})
				}).catch(err => {
					console.log(err)
				})
			},
			/**
			 * 立即购买
			 */
			buy() {
				let This = this
				// console.log(this.productDetails);return;
				if (Object.keys(this.selectAttrValue).length == 0) {
					uni.showToast({
						title: "请先选商品规格",
						icon: "none"
					})
					return;
				}
				if (this.productDetails.product_type == 4) {
					this.buyGoupOrder()
					return;
				}


				let cartData = {
					cart_num: this.num,
					is_new: 1,
					product_attr_unique: this.selectAttrValue.unique,
					product_type: this.productDetails.product_type,
					product_id: this.productDetails.product_id

					// product_id: this.productDetails.product_type == 4 ?
					// this.productDetails.product_group_id : this.productDetails.product_id
				}

				addCartApi(cartData).then(res => {
					let obj = res.data.cartProduct[0]
					let data = {
						address_id: '',
						takes: [],
						cart_id: [res.data.cart_id],
						use_integral: 0,
						use_coupon: []
					}
					data.use_coupon[obj.merchant.mer_id] = []
					return orderCheckApi(data)
				}).then(res => {
					let data = [];
					this.popupShow = false
					res.data.order.forEach(merOrder => {
						merOrder.list.forEach(cartData => {
							data.push(cartData)
						})
						Cache.set('cartToPayCheck', data)
					})
					uni.navigateTo({
						url: '/pages/client/order/order-sure/order-sure'
					})
				}).catch(err => {
					console.log(err)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.boxbg {
		width: 750rpx;
		height: 1100rpx;
		padding-bottom: 0;

		.addcart {
			width: 710rpx;
			height: 100rpx;
			background: linear-gradient(90deg, #2BCCA5 0%, #22B591 100%);
			border-radius: 50rpx;
			font-size: 32rpx;
			font-family: Microsoft YaHei;
			font-weight: 400;
			color: #FFFEFE;
			display: flex;
			margin-left: 20rpx;
			align-items: center;
			justify-content: center;
			margin-top: 50rpx;
		}

		.num {
			width: 710rpx;
			margin-left: 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 30rpx;

			text {
				font-size: 26rpx;
				font-family: Microsoft YaHei;
				font-weight: bold;
				color: #333333;
			}

			&>view {
				display: flex;
				align-items: center;
				justify-content: center;

				input {
					width: 60rpx;
					text-align: center;
					font-size: 26rpx;
					font-family: Microsoft YaHei;
					font-weight: bold;
					color: #333333;
				}

				view {
					width: 42rpx;
					height: 42rpx;



					image {
						width: 42rpx;
						height: 42rpx;
					}
				}
			}
		}

		.item {
			width: 710rpx;
			margin-left: 20rpx;
			display: flex;
			flex-direction: column;
			margin-top: 30rpx;

			text {
				font-size: 26rpx;
				font-family: Microsoft YaHei;
				font-weight: bold;
				color: #333333;
				line-height: 40rpx;
			}

			.actives {
				color: #109C7A !important;
				background: #ECF8F5 !important;
			}

			&>view {
				width: 710rpx;
				display: flex;
				flex-wrap: wrap;

				&>view {
					width: 216rpx;
					height: 54rpx;
					background: #F5F5F5;
					border-radius: 27rpx;
					margin-left: 21rpx;
					display: flex;
					align-items: center !important;
					justify-content: center !important;
					margin-top: 28rpx;
					font-size: 24rpx;
					font-family: Microsoft YaHei;
					font-weight: 400;
					color: #333333;
				}

				&>view:nth-of-type(3n+1) {
					margin-left: 0;
				}
			}
		}



		.head {
			width: 710rpx;
			margin-left: 20rpx;
			display: flex;
			margin-top: 30rpx;
			height: 180rpx;

			image {
				width: 180rpx;
				height: 180rpx;
				background: yellow;
				border-radius: 12rpx;
				margin-right: 30rpx;
			}

			.itemr {
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				height: 180rpx;
				flex: 1;

				.itemr_t {
					display: flex;
					flex-direction: column;
					font-size: 22rpx;
					font-family: Microsoft YaHei;
					font-weight: 400;
					color: #666666;
					line-height: 40rpx;
				}

				.itemr_t text:nth-of-type(1) {
					font-size: 28rpx;
					font-family: Microsoft YaHei;
					font-weight: bold;
					color: #333333;
					line-height: 40rpx;
				}
			}

			.itemr_b {
				font-size: 28rpx;
				font-family: Microsoft YaHei;
				font-weight: bold;
				color: #F83535;
				text-decoration: none;

				text {
					font-size: 24rpx;
					font-family: Microsoft YaHei;
					font-weight: 400;
					text-decoration: line-through;
					color: #999999;
					line-height: 6rpx;
				}
			}
		}



	}
</style>
